<?php

include_file('src/02_class/AJobTool.abstract_class.php');

/**
 * HTMLDocXPathQuerying - Allow easy downloading of file
 * 
 * @uses php-curl
 * @author polux       
 */
class HTMLDocXPathQuerying extends AJobTool {	
	// ***********************  Constructor  *********************** //
	/**
	 * Default Constructor
	 * 
	 * @param AJob 		$p_o_jobObj			Job Object reference
	 */
	function __construct(&$p_o_jobObj) {
		parent::__construct($p_o_jobObj);		
	}
	
	// *********************** Public Methods  *********************** //
	/**
	 * defineMandatoryProperties - Set default properties
	 * 
	 * @see AJobTool::defineMandatoryProperties()
	 */
	function defineMandatoryProperties()
	{
		$this->_as_jobToolPropertiesDef[] = "INPUT_FILE";
		$this->_as_jobToolPropertiesDef[] = "XPATH_QUERY";
	}
	/**
	 * RunJobTool - Download file and save it
	 * 
	 * @param 	$p_as_options	Options
	 * @return array(string)
	 * @see AJobTool::RunJobTool()
	 */
	function RunJobTool($p_as_options)
	{
		// Loading properties
		$this->loadProperties($p_as_options,true,true);		
		
		$l_s_inputfile = $this->getPropertyValue("INPUT_FILE");
		$l_s_xpath = $this->getPropertyValue("XPATH_QUERY");
		
		// Loading file to DOMDocument object
		$l_o_html = new DOMDocument();
		if(!(@$l_o_html->loadHTMLFile($l_s_inputfile)))
		{
			throw new JobToolGenericException("Error during HTML file loading as a DOMDoc (file:'".$l_s_inputfile."').");
		}
		
		// Xpath Query - Find values to download
		$l_o_xpath = new DOMXPath($l_o_html);
		$l_ao_results = $l_o_xpath->query($l_s_xpath);
		
		$l_as_result = array();
		// Check result valid
		if(count($l_ao_results) > 0)
		{
			// for each results => getting URL
			foreach($l_ao_results as $l_o_tmp)
			{
				$l_s_url = "";
				// Attribute value returned
				if($l_o_tmp instanceof DOMAttr)
				{
					$l_s_url =  $l_o_tmp->value;
				}
				elseif($l_o_tmp instanceof DOMElement)
				{
					$l_s_url =  $l_o_tmp->nodeValue;
				}
				else
				{
					throw new JobToolGenericException("XPath result attribute not valid (class: ".get_class($l_o_tmp).").");
				}
		
				$l_as_result[] =$l_s_url;
			}
			
		}
		return $l_as_result;
	}
}

?>